import { FC, PropsWithChildren } from 'react';
import { BrowserRouter as Router, Switch, Route, Redirect, RouteComponentProps } from 'react-router-dom';
import { routes } from './config';
export type IFCRouteProps = PropsWithChildren<RouteComponentProps>;
export type FCRoute = FC<IFCRouteProps>;

export interface IRouteMeta {
  title: string;
}
export interface IRouteChildren {
  routes: string;
}
export interface IRoute {
  path: string;
  isExact?: boolean;
  component?: FCRoute;
  redirect?: string;
  meta?: IRouteMeta;
  children?: IRoute[];
}

const renderRoute = (routes: IRoute[], panrentRoutePath = '') => {
  return routes.map((r: IRoute) => {
    const { path, isExact = true, children = [], redirect, component: Component, meta } = r;
    const isChilren = children && children.length > 0;
    if (!Component) return null;
    if (redirect) {
      return <Redirect key={path} to={path} />;
    }
    let pRoute = panrentRoutePath + path;
    return (
      <Route
        key={pRoute}
        path={pRoute}
        exact={isExact}
        render={(props) => {
          if (meta && meta.title) {
            document.title = meta?.title;
          }
          return <Component {...props}>{isChilren && renderRoute(children, pRoute + '/')}</Component>;
        }}
      />
    );
  });
};

const BasicRoute: FC = (props) => {
  const { children } = props;
  return (
    <Router>
      {children}
      <Switch>{renderRoute(routes)}</Switch>
    </Router>
  );
};

export default BasicRoute;
